package com.zeusee.main.lpr.activity;

import android.app.AlertDialog;
import android.app.Service;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.zeusee.main.lpr.R;
import com.zeusee.main.lpr.bean.PlateInfo;
import com.zeusee.main.lpr.jni.PlateRecognition;

import java.io.IOException;
import java.util.List;

public class CameraPlateActivity extends AppCompatActivity implements Camera.PreviewCallback, SurfaceHolder.Callback {
    public static final String FOCUS_MODE_MACRO = "macro";
    private static final int CAMERA_REQUEST_CODE = 100;
    private int PreviewHeight = 0;
    private int PreviewWidth = 0;
    int SwitchFlag = 0;
    Camera camera = null;
    SurfaceView camerasurface = null;
    long currentTime;
    TextView detectTime;
    private Camera.Size mPreviewSize;
    Camera.Parameters parameters;
    TextView warning;
    Handler handler = new Handler() {
        public void handleMessage(Message message) {
            if (message.what == 200) {
                CameraPlateActivity.this.warning.setVisibility(View.INVISIBLE);
                CameraPlateActivity.this.warning.setText("");
            }
        }
    };

    public void surfaceCreated(SurfaceHolder surfaceHolder) {
    }

    @Override
    public void onResume() {
        super.onResume();
        Camera camera2 = this.camera;
        if (camera2 != null) {
            camera2.startPreview();
        }
    }

    @Override
    public void onPause() {
        Log.i("MainActivity", "Activity On Pasue");
        if (camera != null){
            this.camera.stopPreview();
        }
        super.onPause();
    }


    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        requestWindowFeature(1);
        setContentView(R.layout.activity_camera_plate);
        this.currentTime = System.currentTimeMillis();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, "android.permission.CAMERA") != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{"android.permission.CAMERA"}, CAMERA_REQUEST_CODE);
                Toast.makeText(this, "请确认已经授权拍照", Toast.LENGTH_SHORT).show();
            }else {
                init();
            }
        }else {
            init();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == CAMERA_REQUEST_CODE && grantResults.length > 0){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                init();
            }else {
                Toast.makeText(this, "获取摄像头权限失败", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    private void init(){
        this.detectTime = (TextView) findViewById(R.id.detectTime);
        this.warning = (TextView) findViewById(R.id.infomation);
        this.camerasurface = (SurfaceView) findViewById(R.id.surfaceView2);
        this.camerasurface.getHolder().addCallback(this);
        this.camerasurface.setKeepScreenOn(true);
    }
    private void showRes(String str) {
        if (this.SwitchFlag == 0) {
            this.SwitchFlag = 1;
            new AlertDialog.Builder(this).setTitle((CharSequence) "识别结果").setMessage((CharSequence) str).setOnCancelListener(new DialogInterface.OnCancelListener() {
                public void onCancel(DialogInterface dialogInterface) {
                    CameraPlateActivity.this.SwitchFlag = 0;
                }
            }).show();
        }
    }

    @Override
    public void onPreviewFrame(byte[] bArr, Camera camera2) {
        String str;
        if (System.currentTimeMillis() - this.currentTime > 150) {
            Log.d("test", "detecting");
            long startTimeMillis = System.currentTimeMillis();
            PlateRecognition.getInstance().plateRecognitionWithRaw(bArr, this.PreviewHeight, this.PreviewWidth, 0.8f, 40, 500, 1);
            PlateInfo bestConfidenceInfo = PlateRecognition.getInstance().getBestConfidenceInfo();
            if (bestConfidenceInfo.getErrorCode() == -1) {
                str = (("" + "车牌号:" + bestConfidenceInfo.getPlateName() + "\n") + "置信度:" + String.valueOf(bestConfidenceInfo.getConfidence()) + "\n") + "车牌颜色:" + bestConfidenceInfo.color[bestConfidenceInfo.getPlateType()] + "\n";
            } else {
                str = "";
            }
            if (str != "") {
                if (!this.warning.getText().toString().contains(bestConfidenceInfo.getPlateName())) {
                    ((Vibrator) getSystemService(Service.VIBRATOR_SERVICE)).vibrate(80);
                }
                this.warning.setVisibility(View.VISIBLE);
                this.warning.setText(str);
                this.detectTime.setText("耗时:" + (System.currentTimeMillis() - startTimeMillis) + "ms");
                this.handler.removeCallbacksAndMessages((Object) null);
                this.handler.sendEmptyMessageDelayed(200, 2000);
            }
            this.currentTime = System.currentTimeMillis();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
        this.camera = Camera.open(0);
        this.parameters = this.camera.getParameters();
        this.parameters.setFocusMode(FOCUS_MODE_MACRO);
        this.parameters.setFocusMode("continuous-picture");
        this.camera.setParameters(this.parameters);
        try {
            this.camera.setPreviewDisplay(this.camerasurface.getHolder());
        } catch (IOException e) {
            e.printStackTrace();
        }
        Display defaultDisplay = ((WindowManager) getSystemService(Service.WINDOW_SERVICE)).getDefaultDisplay();
        this.parameters = this.camera.getParameters();
        List<Camera.Size> supportedPreviewSizes = this.parameters.getSupportedPreviewSizes();
        this.camera.setDisplayOrientation(90);
        this.mPreviewSize = getOptimalPreviewSize(supportedPreviewSizes, defaultDisplay.getWidth(), defaultDisplay.getHeight());
        this.PreviewWidth = 640;
        this.PreviewHeight = 480;
        this.parameters.setPreviewSize(this.PreviewWidth, this.PreviewHeight);
        this.parameters.setPictureSize(this.PreviewWidth, this.PreviewHeight);
        this.camera.setParameters(this.parameters);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) this.camerasurface.getLayoutParams();
        int i4 = this.PreviewHeight;
        float width = ((float) defaultDisplay.getWidth()) / ((float) i4);
        layoutParams.height = (int) (((float) this.PreviewWidth) * width);
        layoutParams.width = (int) (((float) i4) * width);
        this.camerasurface.setLayoutParams(layoutParams);
        try {
            this.camera.setPreviewDisplay(this.camerasurface.getHolder());
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        this.camera.startPreview();
        this.camera.setPreviewCallback(this);
    }

    private static Camera.Size getOptimalPreviewSize(List<Camera.Size> list, int i, int i2) {
        double d = ((double) i) / ((double) i2);
        Camera.Size size = null;
        if (list == null) {
            return null;
        }
        double d2 = Double.MAX_VALUE;
        double d3 = Double.MAX_VALUE;
        for (Camera.Size next : list) {
            if (Math.abs((((double) next.width) / ((double) next.height)) - d) <= 0.1d && ((double) Math.abs(next.height - i2)) < d3) {
                d3 = (double) Math.abs(next.height - i2);
                size = next;
            }
        }
        if (size == null) {
            for (Camera.Size next2 : list) {
                if (((double) Math.abs(next2.height - i2)) < d2) {
                    size = next2;
                    d2 = (double) Math.abs(next2.height - i2);
                }
            }
        }
        return size;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        this.camera.stopPreview();
        this.camera.release();
        this.camera = null;
    }
}
